package net.sudot.chess.business.service;

import net.sudot.chess.business.dao.AdminDao;
import net.sudot.chess.business.model.Admin;
import net.sudot.chess.business.model.User;
import net.sudot.chess.exception.BusinessException;
import net.sudot.commons.security.AuthenticationProvider;
import net.sudot.commons.security.Jwt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * 管理员
 *
 * @author tangjialin on 2018-03-21.
 */
@Service
public class AdminService implements AuthenticationProvider {

    @Resource
    private AdminDao adminDao;

    @Override
    public User<Admin> getUser(Object principal) {
        Admin admin = null;
        if (principal instanceof Admin) {
            admin = (Admin) principal;
        } else if (principal instanceof Jwt.Payload) {
            String username = ((Jwt.Payload) principal).getSub();
            try {
                admin = adminDao.find(Long.parseLong(username));
            } catch (Exception e) {
                admin = findByUsername(username);
            }
        } else {
            admin = findByUsername((String) principal);
        }
        return admin;
    }

    @Override
    public Set<String> getPermissions(Object principal) {
        return getPermissions((Admin) principal);
    }

    @Override
    public Set<String> getRoles(Object principal) {
        return getRoles((Admin) principal);
    }

    public Set<String> getPermissions(Admin user) {
        Set<String> permissions = new HashSet<>();
        permissions.add("admin");
        return permissions;
    }

    public Set<String> getRoles(Admin user) {
        return null;
    }

    public boolean supports(Class<?> userClass) {
        return userClass != null && Admin.class.isAssignableFrom(userClass);
    }

    /**
     * 获取管理员信息
     *
     * @param username 管理员登录名
     * @return 返回管理员信息
     */
    public Admin findByUsername(String username) {
        return adminDao.findByUsername(username);
    }

    @Transactional(rollbackFor = Exception.class)
    public Admin save(Admin user) {
        String username = user.getUsername();
        Admin existUser = username == null || username.isEmpty() ? null : findByUsername(username);
        if (existUser != null) { throw new BusinessException("此用户名已使用"); }
        user.setEnabled(true);
        user.setLocked(false);
        user = save(user);
        return user;
    }

}
